package com.weiwei.diancan.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.weiwei.diancan.Contant.ConfigMethod;
import com.weiwei.diancan.R;
import com.weiwei.diancan.adapter.PayAdapter;
import com.weiwei.diancan.base.BaseActivity;
import com.weiwei.diancan.bean.LoginBean;
import com.weiwei.diancan.bean.OrderWapper;
import com.weiwei.diancan.cache.CacheConfig;
import com.weiwei.diancan.http.RetrofitFactory;
import com.weiwei.diancan.utils.ActivityManager;
import com.weiwei.diancan.utils.HttpUtils;
import com.weiwei.diancan.utils.OrderUtils;
import com.weiwei.diancan.utils.PessmionUtils;
import com.weiwei.diancan.view.BeizhuDialog;
import com.weiwei.diancan.view.EmptyLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import weiwei.com.weiweilibrary.views.ToastUtil;

public class PayActivity extends BaseActivity {

    private RecyclerView recycler;
    private TextView tv_pay;
    private List<OrderWapper> oederList;
    private TextView tv_all;
    private TextView tv_has_all;
    private TextView tv_need;
    private TextView add_beizhu;

    private double hasPrice = 0;
    private double notHasPrice = 0;
    private String order_id;
    private EditText et_price;
    private PayAdapter adapter;
    private TextView tv_all_order;
    private int type = 0;

    private boolean hasClear = false;
    private BeizhuDialog beizhuDialog;
    private EmptyLayout emptyLayout;
    private String best_orderId;

    @Override
    public void getData() {
        adapter= new PayAdapter(oederList);
        recycler.setAdapter(adapter);

        hasPrice= 0;
        notHasPrice = 0;

        for(OrderWapper orderWapper:oederList){
            String order_state = orderWapper.getOrder_state();
            String order_price = orderWapper.getOrder_price();
            if(order_state.equals("1")){         //未结账
                notHasPrice+=Double.parseDouble(order_price);
            }else{
                hasPrice+=Double.parseDouble(order_price);
            }
        }

        tv_all.setText("共计：¥"+(notHasPrice+hasPrice));
        tv_has_all.setText("已结账：¥"+hasPrice);
        tv_need.setText("应收合计：¥"+notHasPrice);
        et_price.setVisibility(View.VISIBLE);
        tv_all_order.setVisibility(View.GONE);


            if (notHasPrice == 0) {
                //if (type == 3) {
                    hasClear = true;
                    tv_need.setText("实收合计：¥" + hasPrice);
                    et_price.setVisibility(View.GONE);
                    tv_all_order.setVisibility(View.VISIBLE);
                    tv_pay.setText("清桌");
               // }
            } else {
                hasClear = false;
                tv_pay.setText("结账");

        }

        if(type == 3){
            if(PessmionUtils.check_nomessage(PayActivity.this,"4")){
                tv_pay.setText("结账/清桌");
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getInstance().popOneActivity(this);
    }

    @Override
    public void setListeners() {
        /**
         * 备注
         */
        beizhuDialog.setListener((v, text) -> {
            String s = beizhuDialog.getEt_num().getText().toString();
            if(TextUtils.isEmpty(s)){
                ToastUtil.showToast(PayActivity.this,"请输入备注信息");
                return;
            }
            beizhuDialog.cancel();
            beizhu(best_orderId,text);
        });
        /**
         * 添加备注
         */
        add_beizhu.setOnClickListener(v -> {
            if(!PessmionUtils.check(PayActivity.this,"1")){
                return;
            }
            beizhuDialog.show();
        });
        /**
         * 结账
         */
        tv_pay.setOnClickListener(v->{

            if(!PessmionUtils.check(PayActivity.this,"3")){
                return;
            }
                if (hasClear) {
                    if(!PessmionUtils.check(PayActivity.this,"4")){
                        return;
                    }
                    clearTable(order_id);
                } else {
                    String input_price = et_price.getText().toString();
                    if (TextUtils.isEmpty(input_price)) {
                        ToastUtil.showToast(PayActivity.this, "请输入实收金额");
                        return;
                    }

                    double get_price = Double.parseDouble(input_price);

                    double v1 = notHasPrice - get_price;

                    if (type == 1) {
                        checkout_order_one(order_id, String.valueOf(notHasPrice), input_price, String.valueOf(v1));
                    } else {
                        checkout_order_all(order_id, String.valueOf(notHasPrice), input_price, String.valueOf(v1));
                    }
            }
        });
    }

    @Override
    public void initView() {
        recycler = (RecyclerView)findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.setHasFixedSize(true);
        tv_pay = (TextView)findViewById(R.id.tv_pay);
        tv_all_order=  (TextView)findViewById(R.id.tv_all_order);

        tv_all = (TextView)findViewById(R.id.tv_all);
        tv_has_all = (TextView)findViewById(R.id.tv_has_all);
        tv_need = (TextView)findViewById(R.id.tv_need);
        add_beizhu = (TextView)findViewById(R.id.add_beizhu);
        et_price = (EditText)findViewById(R.id.et_price);
        emptyLayout = (EmptyLayout)findViewById(R.id.emptyLayout);

        beizhuDialog = new BeizhuDialog(this);
        beizhuDialog.getEt_num().setHint(oederList.get(0).getTab_name());
    }

    @Override
    public void initTitle() {
        titler.setText("结账");

        iv_left.setVisibility(View.VISIBLE);
        iv_left.setText("返回");
        iv_left.setOnClickListener(v->finish());
    }

    @Override
    public void setLayoutView() {
        setContentView(R.layout.activity_pay);
        ActivityManager.getInstance().pushOneActivity(this);
        Bundle extras = getIntent().getExtras();
        order_id = extras.getString("order_id");
        best_orderId = order_id;
        type = extras.getInt("type");
        oederList = OrderUtils.getOederList(order_id,type);
        if(type == 1){
            best_orderId = extras.getString("best_orderId");
        }
    }

    /**
     * 全部结账
     */
    private void checkout_order_all(String orderId,String order_2,String order_price,String order_1){
        progressDialog.setMessage("结账中...");
        progressDialog.show();
        Map<String,String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token,CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token,CacheConfig.getInst().getWaterToken(this));
        map.put(ConfigMethod.order_id,orderId);
        map.put(ConfigMethod.order_2,order_2);
        map.put(ConfigMethod.order_price,order_price);
        map.put(ConfigMethod.order_1,order_1);
        RetrofitFactory.getIntance().checkout_order_all(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        progressDialog.cancel();
                        HttpUtils.check(loginBean, PayActivity.this, loginBean1 -> {
                            ToastUtil.showToast(PayActivity.this,loginBean1.getReason());
                            oederList = OrderUtils.getOederList(order_id,type);
                            et_price.setText("");
                            getData();
                            if(type == 3){
                                if(PessmionUtils.check_nomessage(PayActivity.this,"4")){
                                    clearTable(orderId);
                                }else{
                                    finish();
                                }
                            }else{
                                if(!PessmionUtils.check_nomessage(PayActivity.this,"4")){
                                    finish();
                                }
                            }
                        });
                    }
                });
    }

    /**
     * 单个订单结账
     */
    private void checkout_order_one(String orderId,String order_2,String order_price,String order_1){
        progressDialog.setMessage("结账中...");
        progressDialog.show();
        Map<String,String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token,CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token,CacheConfig.getInst().getWaterToken(this));
        map.put(ConfigMethod.order_id,orderId);
        map.put(ConfigMethod.order_2,order_2);
        map.put(ConfigMethod.order_price,order_price);
        map.put(ConfigMethod.order_1,order_1);
        RetrofitFactory.getIntance().checkout_order_one(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        progressDialog.cancel();
                        HttpUtils.check(loginBean, PayActivity.this, loginBean1 -> {
                            ToastUtil.showToast(PayActivity.this,loginBean1.getReason());
                            finish();
                        });
                    }
                });
    }

    /**
     * 清桌
     */
    private void clearTable(String orderId){

        progressDialog.setMessage("清桌中...");
        progressDialog.show();
        Map<String,String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token,CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token,CacheConfig.getInst().getWaterToken(this));
        map.put(ConfigMethod.order_id,orderId);
        RetrofitFactory.getIntance().clean_table(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        progressDialog.cancel();
                        HttpUtils.check(loginBean, PayActivity.this, loginBean1 -> {
                            ToastUtil.showToast(PayActivity.this,loginBean1.getReason());
//                            EventBus.getDefault().post("finish");
//                            finish();
                            ActivityManager.getInstance().finishAllActivity();
                        });
                    }
                });
    }

    /**
     * 备注
     */
    private void beizhu(String orderId,String log_desc){
        progressDialog.setMessage("备注上传中...");
        progressDialog.show();
        Map<String,String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token,CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token,CacheConfig.getInst().getWaterToken(this));
        map.put(ConfigMethod.order_id,orderId);
        map.put(ConfigMethod.log_desc, log_desc);
        RetrofitFactory.getIntance().add_order_log(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                        emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR,-1);
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        progressDialog.cancel();
                        HttpUtils.check(loginBean, PayActivity.this, loginBean1 -> {
                            ToastUtil.showToast(PayActivity.this,loginBean1.getReason());
                            add_beizhu.setText("备注信息:"+log_desc);
                        });
                    }
                });
    }
}
